<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use think\Exception;
use think\Log;
use app\admin\model\Company;
use think\Db;

/**
 * 订单列管理
 *
 * @icon fa fa-circle-o
 */
class Main extends Backend
{

    /**
     * Main模型对象
     * @var \app\admin\model\order\Main
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Main;
        if ($this->auth->getGroupId() == ATTACHE_GROUP_ID) {
            $this->dataLimit = true;
            $this->dataLimitField = 'attache_id';
        } else if ($this->auth->getGroupId() == COMPANY_GROUP_ID) {
            $this->dataLimit = true;
        } else {
            $this->dataLimit = false;
        }
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }

        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $company = null;
        $total_price = 0;
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);

            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if ($row) {
                //厂商

                $row['attribute_id'] = intval($row['attribute_id']);
                $row['trademark_id'] = intval($row['trademark_id']);

                $row['tel'] = intval($row['tel']);
                $row['attribute_id'] = intval($row['attribute_id']);
                $row['admin_id'] = Db::name('order_trademark')->where('id', $row['trademark_id'])->value('admin_id');
                if (!$row['admin_id']) {
                    $this->error(__('品牌不存在，请检查！'));
                }
                if ($company == null) {
                    $company = Company::get(['admin_id' => $row['admin_id']]);
                }
                if ($this->auth->getGroupId() == COMPANY_GROUP_ID)//如果是商家，需要判断一下这个品牌是不是属于这个商家
                {
                    if ($row['admin_id'] != $this->auth->id) {
                        $this->error(__('品牌错误，请检查！'));
                    }
                }
                //品类
                $row['category_id'] = Db::name('order_attribute')->where('id', $row['attribute_id'])->value('category_id');
                $row['category_second_id'] = Db::name('order_category')->where('id', $row['category_id'])->value('pid');
                $row['category_first_id'] = Db::name('order_category')->where('id', $row['category_second_id'])->value('pid');
                //价格
                $row['price'] = bcmul(Db::name('order_attribute')->where('id', $row['attribute_id'])->value('price'), $row['quantity'], 2);
                //编号
                list($msec, $sec) = explode(' ', microtime());
                $row['code'] = date('YmdHis') . round($msec * 1000);
                //生成时间
                $row['create_time'] = date('Y-m-d H:i:s');
                $row['service_time'] = date('Y-m-d H:i:s');
                $insert[] = $row;
                $total_price += $row['price'];
            }
        }

        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        if ($company['balance'] < $total_price) {
            $this->error('余额不足，请充值！');
        }
        Db::startTrans();
        try {
            Company::balance(-$total_price, $company['admin_id'], '批量发布订单');
            $ret = $this->model->saveAll($insert);
            if (!$ret) {
                Db::rollback();
                $this->error($this->model->getError());
            }
            Db::commit();
        } catch (\think\exception\PDOException $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    public function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", "id");
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = (array)json_decode($filter, TRUE);
        $op = (array)json_decode($op, TRUE);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        if (isset($filter['admin.company.id'])) {
            $filter['admin.id'] = Db::name('company')->where('id', $filter['admin.company.id'])->value('admin_id');
            unset($filter['admin.company.id']);
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '!=':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $total_price = 0;
        $total_money = 0;
        $isCompany = false;
        $isAttache = false;
        $isSeniorAdmin = false;
        if ($this->auth->getGroupId() == SENIOR_GROUP_ID)
            $isSeniorAdmin = true;
        elseif ($this->auth->getGroupId() == COMPANY_GROUP_ID)
            $isCompany = true;
        elseif ($this->auth->getGroupId() == ATTACHE_GROUP_ID)
            $isAttache = true;
        $this->assignconfig([
            'isSeniorAdmin' => $isSeniorAdmin,
            'isCompany' => $isCompany,
            'isAttache' => $isAttache,
        ]);
        if ($this->request->isAjax()) {
            try {

                //如果发送的来源是Selectpage，则转发到Selectpage
                if ($this->request->request('keyField')) {
                    return $this->selectpage();
                }
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                    ->with(['admin', 'attribute', 'trademark', 'attache', 'province', 'city', 'country'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $total_price = $this->model
                    ->with(['admin', 'attribute', 'trademark', 'attache', 'province', 'city', 'country'])
                    ->where($where)
                    ->order($sort, $order)
                    ->sum('main.price');
                $total_money = $this->model
                    ->with(['admin', 'attribute', 'trademark', 'attache', 'province', 'city', 'country'])
                    ->where($where)
                    ->order($sort, $order)
                    ->sum('main.voucher_content');
                $list = $this->model
                    ->with(['admin', 'attribute', 'trademark', 'attache', 'province', 'city', 'country'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

                foreach ($list as $row) {
                    try {
                        $row->admin->company;
                        $row->attribute->category->myPid->myPid = \app\admin\model\order\Category::get($row->attribute->category->myPid->pid);
                    } catch (\Exception $e) {
                        dump($row->attribute);
                    }
                    if ($row->status == ORDER_COMPLETE || $row->status == ORDER_CANCEL) {
                        if ($isCompany) {
                            $row->mobile = '-';
                        }
                    }
                }
                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list, 'total_money' => $total_money, 'total_price' => $total_price);
//            $result = array("total" => $total, "rows" => $list);
                return json($result);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }

        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->auth->getGroupId() != COMPANY_GROUP_ID) {//现在的需求是不是管理员也可以发布订单，但要具有权限。
            // $this->error('非厂商不能发布订单。请联系管理员取消权限。');
            $this->assign('is_company', false);
        } else {
            $this->assign('is_company', true);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->auth->getGroupId() == COMPANY_GROUP_ID) {
                    $params['admin_id'] = $this->auth->id;
                } elseif (!$params['admin_id']) {
                    $this->error(__('Parameter %s can not be empty', ''));
                }
                try {
                    list($msec, $sec) = explode(' ', microtime());
                    $admin = \app\admin\model\Admin::get(intval($params['admin_id']));
                    $company = $admin->company;
                    $balance = floatval($admin->company->balance);
                    $params['category_first_id'] = $this->request->post('first');
                    $params['category_second_id'] = $this->request->post('second');
                    $params['category_id'] = $this->request->post('category_id');
                    $params['attribute_id'] = $this->request->post('attribute_id');
                    $params['price'] = Db::name('order_attribute')->where('id', $params['attribute_id'])->value('price') * $params['quantity'];
                    $params['code'] = date('YmdHis') . round($msec * 1000);
                    if ($balance < $params['price']) {
                        $this->error('余额不足，请充值！');
                    }
//                    if ($balance < 200) {
//                        $this->error('余额不足200，请先充值！');
//                    }
                    $params['create_time'] = date('Y-m-d H:i:s');
                    $this->request->post('province') ? $params['province_id'] = $this->request->post('province') : '';
                    $this->request->post('city') ? $params['city_id'] = $this->request->post('city') : '';
                    $this->request->post('area') ? $params['country_id'] = $this->request->post('area') : '';

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    Db::startTrans();
                    $result = $this->model->allowField(true)->save($params);

                    if ($result !== false) {
                        Company::balance(-$params['price'], $params['admin_id'], '发布订单');
//                            \think\Hook::listen('order_create', $this->model->id);
                        Db::commit();
                        $this->success('订单发布成功！余额减少' . $params['price'] . '元，余额为：' . $company->balance . '元');
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $this->request->post('province') ? $params['province_id'] = $this->request->post('province') : '';
                    $this->request->post('city') ? $params['city_id'] = $this->request->post('city') : '';
                    $this->request->post('area') ? $params['country_id'] = $this->request->post('area') : '';

                    !$params['service_time'] ? $params['service_time'] = date('Y-m-d H:i:s') : $params['service_time'];

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        foreach ($row as $item) {
            $item->attribute->category->mypid;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 指派订单
     */
    public function designate()
    {
        if ($this->request->isPost()) {
            $attache_id = $this->request->post("attache_id");
            $ids = $this->request->param('ids');
            $ids = explode(',', $ids);
            $total = count($ids);
            $no_attache = 0;
            if ($attache_id) {
                try {
                    $orders = $this->model->all($ids);
                    $orders = collection($orders)->toArray();
                    $save_orders = array();
                    foreach ($orders as $key => $value) {
                        if ($value['attache_id'] == null) {
                            $value['attache_id'] = $attache_id;
                            $value['status'] = ORDER_DESIGNATE_YES;
                            $value['designate_time'] = date('Y-m-d H:i:s');
                            unset($value['flag']);
                            $save_orders[] = $value;
                        } else if ($value['status'] == ORDER_DESIGNATE_YES) {
                            $value['attache_id'] = $attache_id;
                            $value['status'] = ORDER_DESIGNATE_YES;
                            $value['designate_time'] = date('Y-m-d H:i:s');
                            unset($value['flag']);
                            $save_orders[] = $value;
                        } else {
                            $no_attache++;
                        }
                    }
                    $result = $this->model->allowField(true)->saveAll($save_orders);
                    if (!$result) {
                        $this->error('没有需要指派的订单');
                    }
                    $this->success('共指派' . $total . '个订单，其中' . $no_attache . '不能重新指派，被忽略。');
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 添加师傅电话
     */
    public function mobile($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $mobile = $this->request->post("mobile");

            if ($mobile) {
                try {
                    $row->mobile = $mobile;
                    $result = $row->isUpdate(true)->save();
                    if (!$result) {
                        $this->error($row->getError());
                    }
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 反馈信息
     */
    public function feedback()
    {
        if ($this->request->isPost()) {
            $feedback_images = $this->request->post("feedback_images");
            $feedback_content = $this->request->post("feedback_content");
            $order_id = $this->request->param('ids');
            $order = $this->model->get($order_id);
            if ($order->status != ORDER_DESIGNATE_YES) {
                $this->error('只有已派单才可以反馈信息');
            }
            if ($feedback_images || $feedback_content) {
                try {
                    $result = $this->model->update(['id' => $order_id, 'feedback_images' => $feedback_images, 'feedback_content' => $feedback_content]);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 上传完成照片
     */
    public function complete()
    {
        if ($this->request->isPost()) {
            $images = $this->request->post("images");
            $order_id = $this->request->param('ids');
            if ($images) {
                try {
                    $result = $this->model->update(['id' => $order_id, 'images' => $images, 'complete_time' => date('Y-m-d H:i:s'), 'status' => ORDER_COMPLETE]);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 上传收款凭证
     */
    public function voucher()
    {
        if ($this->request->isPost()) {
            $images = $this->request->post("voucher");
            $voucher_content = $this->request->post("voucher_content");
            $order_id = $this->request->param('ids');
            if ($images && $voucher_content) {
                try {
                    $result = $this->model->update(['id' => $order_id, 'voucher' => $images, 'voucher_content' => $voucher_content]);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        if ($this->request->isPost()) {
            $order_id = $this->request->param('ids');
            if ($order_id) {
                \think\Db::startTrans();
                try {
                    $order = $this->model->get($order_id);
                    if (ORDER_DESIGNATE_NO - 1 < $order->status && $order->status < ORDER_COMPLETE) {
                        $result = $this->model->update(['id' => $order_id, 'complete_time' => date('Y-m-d H:i:s'), 'status' => ORDER_CANCEL]);
                        if (!$result) {
                            \think\Db::rollback();
                            $this->error($this->model->getError());
                        } else {
                            $result = \think\Db::name('company')->where('admin_id', $order->admin_id)->setInc('balance', $order->price);
                            if (!$result) {
                                \think\Db::rollback();
                                $this->error('厂商账号异常，请检查厂商是否存在。');
                            } else {
                                \think\Hook::listen('order_cancel', $order_id);
                                \think\Db::commit();
                                $this->success();
                            }
                        }
                    } else {
                        \think\Db::rollback();
                        $this->error('订单状态异常，请检查订单是否已完成或已取消。');
                    }
                } catch (\think\exception\PDOException $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 标记订单
     */
    public function flag()
    {
        if ($this->request->isPost()) {
            $order_id = $this->request->param('ids');
            if ($order_id) {
                try {
                    $order = $this->model->get($order_id);
                    $order->setAttr('flag', 2);
                    $order->isUpdate(true)->save();
                    $this->success();
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
